import { Graph, DataUri } from '@antv/x6'
import { NodeConfig } from './nodeConfig'
import { EdgeConfig } from './edgeConfig'
import { Group } from './groupNode'

/**
 * 图形管理器
 */
export class GraphManager {
  constructor(container, options = {}) {
    this.graph = null
    this.container = container
    this.options = options
    this.currentZoom = 1
    this.selectedCount = 0
    this.currentEdgeType = 'normal'
    this.isDragging = false
    this.dragType = ''
    this.layoutManager = null
    
    this.initGraph()
  }

  /**
   * 设置布局管理器
   */
  setLayoutManager(layoutManager) {
    this.layoutManager = layoutManager
  }

  /**
   * 初始化图形
   */
  initGraph() {
    this.initializeGraph()
  }

  /**
   * 初始化图形设置
   */
  initializeGraph() {
    
    this.graph = new Graph({
      container: this.container,
      grid: { visible: true },
      // 启用画布平移
      panning: {
        enabled: true,
        modifiers: 'shift',
        eventTypes: ['leftMouseDown']
      },
      // 启用鼠标滚轮缩放
      mousewheel: {
        enabled: true,
        modifiers: 'ctrl',
        zoomAtMousePosition: true,
        guard: (e) => e.ctrlKey
      },
      selecting: {
        enabled: true,
        multiple: true,
        rubberband: true,
        movable: true,
        showNodeSelectionBox: true,
        showEdgeSelectionBox: true,
      },
      resizing: {
        enabled: true,
        minWidth: 100,
        minHeight: 60,
        maxWidth: 800,
        maxHeight: 600,
        orthogonal: false,
        restrict: false,
        preserveAspectRatio: false,
        allowNegative: false,
      },
      // 禁用Group嵌套功能 - 不允许外部节点自动进入组内
      embedding: {
        enabled: false,
      },
      // 限制子节点移动范围
      translating: {
        restrict(view) {
          // 添加安全检查，确保view存在
          if (!view || !view.cell) {
            return null
          }
          
          const cell = view.cell
          if (cell.isNode()) {
            const parent = cell.getParent()
            if (parent && parent.isNode()) {
              return parent.getBBox()
            }
          }
          return null
        },
      },
      connecting: {
        enabled: true,
        snap: true,
        allowBlank: false,
        allowLoop: false,
        highlight: true,
        connector: 'smooth',
        validateConnection: ({ sourceView, targetView, sourceMagnet, targetMagnet }) => {
          // 只允许从输出端口连接到输入端口
          if (sourceMagnet && targetMagnet) {
            const sourcePortGroup = sourceMagnet.getAttribute('port-group') ||
              sourceMagnet.getAttribute('data-port-group') ||
              sourceMagnet.getAttribute('group')
            const targetPortGroup = targetMagnet.getAttribute('port-group') ||
              targetMagnet.getAttribute('data-port-group') ||
              targetMagnet.getAttribute('group')
            if (!(sourcePortGroup === 'out' && targetPortGroup === 'in')) {
              return false
            }
          }

          // 获取节点id
          const sourceId = sourceView?.cell?.id
          const targetId = targetView?.cell?.id

          // 禁止自连
          if (sourceId === targetId) {
            return false
          }

          // 禁止+号图标被连线
          const sourceCell = sourceView?.cell
          const targetCell = targetView?.cell
          
          // 检查源节点或目标节点是否为+号图标
          if (sourceCell && sourceCell.getData && sourceCell.getData('isPlusIcon')) {
            return false
          }
          
          if (targetCell && targetCell.getData && targetCell.getData('isPlusIcon')) {
            return false
          }

          // 检查从targetView是否有路径能到达sourceView（防止环路）
          // 尝试多种方式获取graph对象
          let graph = sourceView?.cell?.graph
          if (!graph) {
            graph = sourceView?.graph
          }
          if (!graph) {
            graph = targetView?.cell?.graph
          }
          if (!graph) {
            graph = targetView?.graph
          }
          if (!graph) {
            // 如果还是获取不到，使用this.graph
            graph = this.graph
          }
          
          if (graph && sourceId && targetId) {
            const visited = new Set()
            
            function canReachSource(currentId) {
              // 如果当前节点就是源节点，说明找到了路径
              if (currentId === sourceId) {
                return true
              }
              
              // 如果已经访问过，避免重复访问
              if (visited.has(currentId)) {
                return false
              }
              
              visited.add(currentId)
              
              // 获取当前节点的所有出边
              const outEdges = graph.getOutgoingEdges(currentId)
              if (!outEdges || outEdges.length === 0) {
                return false
              }
              
              // 遍历所有出边，检查是否能到达源节点
              for (const edge of outEdges) {
                const nextId = edge.getTargetCellId()
                if (nextId && canReachSource(nextId)) {
                  return true
                }
              }
              
              return false
            }
            
            // 从目标节点开始检查是否能到达源节点
            if (canReachSource(targetId)) {
              // 如果从目标节点能到达源节点，说明会形成环路，禁止连线
              return false
            }
          }

          return true
        },
      },
      // 启用撤销/重做功能
      history: {
        enabled: true,
        ignoreAdd: false,
        ignoreRemove: false,
        ignoreChange: false,
      },
    })

    this.bindEvents()
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 监听缩放变化
    this.graph.on('scale', () => {
      this.currentZoom = this.graph.zoom()
    })

    // 监听选择变化
    this.graph.on('selection:changed', () => {
      this.updateSelectedCount()
    })
    
    // 监听Group节点自动扩展
    this.graph.on('node:change:size', ({ node, options }) => {
      if (options.skipParentHandler) {
        return
      }

      const children = node.getChildren()
      if (children && children.length) {
        node.prop('originSize', node.getSize())
      }
    })

    this.graph.on('node:change:position', ({ node, options }) => {
      if (options.skipParentHandler) {
        return
      }

      const children = node.getChildren()
      if (children && children.length) {
        node.prop('originPosition', node.getPosition())
      }

      const parent = node.getParent()
      if (parent && parent.isNode()) {
        let originSize = parent.prop('originSize')
        if (originSize == null) {
          parent.prop('originSize', parent.getSize())
        }
        originSize = parent.prop('originSize')

        let originPosition = parent.prop('originPosition')
        if (originPosition == null) {
          parent.prop('originPosition', parent.getPosition())
        }
        originPosition = parent.prop('originPosition')

        let x = originPosition.x
        let y = originPosition.y
        let cornerX = originPosition.x + originSize.width
        let cornerY = originPosition.y + originSize.height
        let hasChange = false

        const children = parent.getChildren()
        if (children) {
          children.forEach((child) => {
            const bbox = child.getBBox()
            const corner = bbox.getCorner()

            if (bbox.x < x) {
              x = bbox.x
              hasChange = true
            }

            if (bbox.y < y) {
              y = bbox.y
              hasChange = true
            }

            if (corner.x > cornerX) {
              cornerX = corner.x
              hasChange = true
            }

            if (corner.y > cornerY) {
              cornerY = corner.y
              hasChange = true
            }
          })
        }

        if (hasChange) {
          parent.prop(
            {
              position: { x, y },
              size: { width: cornerX - x, height: cornerY - y },
            },
            // Note that we also pass a flag so that we know we shouldn't 
            // adjust the `originPosition` and `originSize` in our handlers.
            { skipParentHandler: true },
          )
        }
      }
    })

    // 监听端口连接事件
    this.graph.on('edge:connected', ({ edge }) => {
      const edgeConfig = EdgeConfig.getEdgeConfig(edge.getSourceCell(), edge.getTargetCell(), this.currentEdgeType)
      try {
        edge.setAttrs(edgeConfig.attrs)
        if (edgeConfig.router) {
          edge.setRouter(edgeConfig.router)
        }
        if (edgeConfig.connector) {
          edge.setConnector(edgeConfig.connector)
        }
      } catch (error) {
        console.warn('设置连线配置失败:', error)
      }
      
      // 延迟添加连线中间的加号图标，确保连线路径已经计算完成
      setTimeout(() => {
        this.addPlusIconToEdge(edge)
      }, 200)
    })

    // 监听连线移动事件，更新加号图标位置
    this.graph.on('edge:change:vertices', ({ edge }) => {
      this.updatePlusIconPosition(edge)
    })

    // 监听连线位置变化事件
    this.graph.on('edge:change:position', ({ edge }) => {
      this.updatePlusIconPosition(edge)
    })

    // 监听连线源节点或目标节点变化事件
    this.graph.on('edge:change:source', ({ edge }) => {
      setTimeout(() => {
        this.updatePlusIconPosition(edge)
      }, 50)
    })

    this.graph.on('edge:change:target', ({ edge }) => {
      setTimeout(() => {
        this.updatePlusIconPosition(edge)
      }, 50)
    })

    // 监听节点移动事件，更新相关连线的加号标签位置
    this.graph.on('node:change:position', ({ node }) => {
      // 如果是普通节点移动，延迟更新所有相关连线的加号标签位置
      setTimeout(() => {
        this.updateAllRelatedPlusIcons(node)
      }, 50)
    })

    // 监听节点大小变化事件，特别是组节点
    this.graph.on('node:change:size', ({ node }) => {
      // 如果是组节点大小变化，更新所有相关连线的加号图标位置
      const nodeData = node.getData()
      if (nodeData && nodeData.type === 'group') {
        setTimeout(() => {
          this.updateAllRelatedPlusIcons(node)
        }, 100)
      }
    })



    // 监听历史状态变化
    if (this.graph.history) {
      this.graph.history.on('change', () => {
        // 触发自定义事件，通知 UI 更新
        this.graph.trigger('history:changed')
      })
    }

    // 监听节点删除事件
    this.graph.on('cell:removed', () => {
      // 延迟检查，确保删除操作完成
      setTimeout(() => {
        this.checkAndConnectStartEnd()
      }, 100)
    })

    // 监听节点点击事件，确保能正确触发
    this.graph.on('node:click', ({ node, e }) => {
      // 阻止事件冒泡，确保点击事件能被正确处理
      if (e) {
        e.stopPropagation()
      }
    })
  }

  /**
   * 为连线添加中间加号标签
   * @param {Object} edge 连线对象
   */
  addPlusIconToEdge(edge) {
    // 延迟添加，确保连线路径已经计算完成
    setTimeout(() => {
      try {
        // 检查连线是否已经有+号标签
        const hasPlusIcon = edge.getData('hasPlusIcon')
        if (hasPlusIcon) {
          // 如果已经有+号标签，只更新位置
          this.updatePlusIconPosition(edge)
          return
        }
        
        // 设置标签位置为连线中间
        edge.setLabels([
          {
            position: 0.5, // 连线中间位置
            attrs: {
              label: {
                text: '➕', // 使用简单的+号
                fill: '#ffffff',
                fontSize: 16,
                fontWeight: 'bold',
                textAnchor: 'middle',
                textVerticalAnchor: 'middle',
                cursor: 'pointer',
                // 添加圆形背景
                background: {
                  fill: '#5F95FF',
                  stroke: '#5F95FF',
                  strokeWidth: 2,
                  rx: 10,
                  ry: 10,
                  // 添加阴影效果
                  filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.1))'
                }
              }
            }
          }
        ])
        
        // 添加自定义属性标识
        edge.setData('hasPlusIcon', true)
        
        // 强制刷新连线显示，确保+号立即显示
        setTimeout(() => {
          edge.setLabels([
            {
              position: 0.5,
              attrs: {
                label: {
                  text: '➕',
                  fill: '#ffffff',
                  fontSize: 16,
                  fontWeight: 'bold',
                  textAnchor: 'middle',
                  textVerticalAnchor: 'middle',
                  cursor: 'pointer',
                  background: {
                    fill: '#5F95FF',
                    stroke: '#5F95FF',
                    strokeWidth: 2,
                    rx: 10,
                    ry: 10,
                    filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.1))'
                  }
                }
              }
            }
          ])
        }, 100)
        
        // 监听连线的点击事件
        edge.on('click', (e) => {
          // 检查点击位置是否在标签附近
          const point = this.graph.clientToLocal(e.clientX, e.clientY)
          const labelPosition = edge.getLabels()[0]
          
          if (labelPosition) {
            const labelBBox = edge.getBBox()
            const labelX = labelBBox.x + labelBBox.width * 0.5
            const labelY = labelBBox.y + labelBBox.height * 0.5
            
            const distance = Math.sqrt(
              Math.pow(point.x - labelX, 2) + Math.pow(point.y - labelY, 2)
            )
            
            // 如果点击位置在标签附近（20像素范围内），触发+号点击事件
            if (distance <= 20) {
              e.stopPropagation()
              e.preventDefault()
              this.onPlusIconClick(edge, e)
            }
          }
        })

      } catch (error) {
        console.error('添加加号标签失败:', error)
      }
    }, 100)
  }

  /**
   * 更新连线中间加号标签位置
   * @param {Object} edge 连线对象
   */
  updatePlusIconPosition(edge) {
    // 检查连线是否仍然存在
    if (!edge || !edge.isEdge()) {
      console.warn('连线不存在或已被删除')
      return
    }
    
    // 检查连线是否有+号标签
    const hasPlusIcon = edge.getData('hasPlusIcon')
    if (!hasPlusIcon) {
      return
    }
    
    // 对于label，位置是相对于连线的，不需要手动计算位置
    // 只需要确保标签在连线中间
    try {
      const labels = edge.getLabels()
      if (labels && labels.length > 0) {
        // 确保标签位置在连线中间
        edge.setLabels([
          {
            position: 0.5, // 连线中间位置
            attrs: {
              label: {
                text: '➕', // 使用简单的+号
                fill: '#ffffff',
                fontSize: 14,
                fontWeight: 'bold',
                textAnchor: 'middle',
                textVerticalAnchor: 'middle',
                cursor: 'pointer',
                // 添加圆形背景
                background: {
                  fill: '#5F95FF',
                  stroke: '#5F95FF',
                  strokeWidth: 2,
                  rx: 10,
                  ry: 10,
                  // 添加阴影效果
                  filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.1))'
                }
              }
            }
          }
        ])
        console.log('更新+号标签位置到连线中间')
      }
    } catch (error) {
      console.warn('无法更新+号标签位置:', error)
    }
  }

  /**
   * 更新所有相关连线的加号标签位置
   * @param {Object} node 移动的节点
   */
  updateAllRelatedPlusIcons(node) {
    // 获取所有与当前节点相关的连线
    const edges = this.graph.getEdges()
    edges.forEach(edge => {
      // 检查连线是否仍然有效
      if (!edge || !edge.isEdge()) {
        return
      }
      
      const source = edge.getSourceCell()
      const target = edge.getTargetCell()
      
      // 如果连线与移动的节点相关，更新其加号标签位置
      if (source === node || target === node) {
        this.updatePlusIconPosition(edge)
      }
    })
  }

  /**
   * 检查节点是否在组内
   * @param {Node} node 要检查的节点
   * @returns {boolean} 是否在组内
   */
  isNodeInGroup(node) {
    if (!node) {

      return false
    }
    
    
    
    // 检查节点是否有父节点（组节点）
    const parent = node.getParent()
    
    
    if (parent && parent.isNode()) {
      // 检查父节点是否是组节点
      const parentData = parent.getData()
      
      const isGroup = parentData && parentData.type === 'group'
      
      return isGroup
    }
    

    return false
  }

  /**
   * 获取连线两端节点的位置信息
   * @param {Edge} edge 连线对象
   * @returns {Object} 包含sourceInGroup和targetInGroup的对象
   */
  getEdgeNodesLocation(edge) {
    if (!edge) {
      return { sourceInGroup: false, targetInGroup: false }
    }
    
    const sourceId = edge.getSourceCellId()
    const targetId = edge.getTargetCellId()
    
    const sourceNode = this.graph.getCellById(sourceId)
    const targetNode = this.graph.getCellById(targetId)
    
    const sourceInGroup = this.isNodeInGroup(sourceNode)
    const targetInGroup = this.isNodeInGroup(targetNode)
    
    
    return {
      sourceInGroup,
      targetInGroup
    }
  }

  /**
   * 处理连线中间加号标签点击事件
   * @param {Object} edge 连线对象
   */
  onPlusIconClick(edge, event) {
    // 现在edge参数直接是连线对象，因为+号是连线的label
    
    if (!edge || !edge.isEdge()) {
      console.warn('传入的对象不是有效的连线')
      return
    }

    // 检查连线两端节点的位置
    const locationInfo = this.getEdgeNodesLocation(edge)

    // 使用鼠标事件的位置
    let position = { x: 0, y: 0 }
    
    if (event && event.clientX !== undefined && event.clientY !== undefined) {
      // 使用鼠标事件的位置
      position = { x: event.clientX, y: event.clientY }
      console.log('✅ 使用鼠标事件位置:', position)
    } else {
      console.log('⚠️ 没有鼠标事件，使用计算位置')
      // 如果没有鼠标事件，则使用加号图标的位置作为备选
      const center = EdgeConfig.getEdgeCenter(edge)
      console.log('连线中心位置:', center)
      
      if (center) {
        const container = this.graph.container
        const containerRect = container.getBoundingClientRect()
        const zoom = this.graph.zoom()
        
        console.log('画布容器位置:', containerRect)
        console.log('缩放比例:', zoom)
        
        position = {
          x: containerRect.left + (center.x * zoom),
          y: containerRect.top + (center.y * zoom)
        }
      }
    }
    
    // 触发自定义事件，通知 UI 显示节点选择器
    this.graph.trigger('plus-icon-clicked', {
      edge,
      position: position,
      node,
      locationInfo // 添加位置信息
    })
  }

  /**
   * 更新选中数量
   */
  updateSelectedCount() {
    this.selectedCount = this.graph.getSelectedCells().length
  }

  /**
   * 添加节点
   * @param {Object} config 节点配置
   */
  addNode(config) {
    return this.graph.addNode(config)
  }

  /**
   * 创建Group节点并初始化普通节点
   * @param {number} x X坐标
   * @param {number} y Y坐标
   * @param {string} nodeType 普通节点类型
   * @param {string} nodeLabel 普通节点标签
   * @param {Node} sourceNode 源节点（可选）
   * @param {Node} targetNode 目标节点（可选）
   * @returns {Object} 包含group和newEdges的对象
   */
  createGroupWithNode(x, y, nodeType, nodeLabel, sourceNode = null, targetNode = null) {
    // 创建Group节点 - 使用标准节点配置
    const groupConfig = {
      x: x,
      y: y,
      width: 400,
      height: 300,
      label: '组节点',
      zIndex: 1,
      data: {
        type: 'group',
        parent: true
      },
      attrs: {
        body: {
          fill: '#f0f8ff',
          stroke: '#5F95FF',
          strokeWidth: 2,
          rx: 8,
          ry: 8,
        },
        label: {
          fontSize: 12,
          fill: '#333',
          textAnchor: 'middle',
          textVerticalAnchor: 'middle',
        },
      },
      // 添加resize功能
      resizing: {
        enabled: true,
        minWidth: 100,
        minHeight: 60,
        maxWidth: 800,
        maxHeight: 600,
        orthogonal: false,
        restrict: false,
        preserveAspectRatio: false,
        allowNegative: false,
      },
      ports: {
        groups: {},
        items: [],
      },
    }
    
    const group = this.graph.addNode(groupConfig)
    
    // 为Group节点添加初始业务数据
    if (this.onNodeCreated) {
      const initialData = {
        label: '组节点',
        type: 'group',
        inputVariables: [],
        outputVariables: [],
        groupSettings: {
          groupType: 'array',
          arrayObject: '',
          itemVariable: '',
          indexVariable: '',
          fixedCount: 1
        }
      }
      this.onNodeCreated(group.id, initialData)
    }
    
    // 在Group中心创建普通节点
    const centerX = x + 200 - 50 // Group中心X - 节点宽度的一半
    const centerY = y + 150 - 25 // Group中心Y - 节点高度的一半
    const mainNode = this.createNodeByType(nodeType, nodeLabel, centerX, centerY)
    group.addChild(mainNode)
    
    // 重新连接节点到组内的新节点
    const newEdges = this.reconnectStartEndToGroupNode(mainNode, sourceNode, targetNode)
    
    return { group, newEdges }
  }

  /**
   * 创建Group节点
   * @param {string} label 组标签
   * @param {number} x X坐标
   * @param {number} y Y坐标
   * @returns {Node} 创建的Group节点
   */
  createGroup(label, x, y) {
    // 创建Group节点 - 使用标准节点配置
    const groupConfig = {
      x: x,
      y: y,
      width: 400,
      height: 300,
      label: label || '组节点',
      zIndex: 1,
      data: {
        type: 'group',
        parent: true
      },
      attrs: {
        body: {
          fill: '#f0f8ff',
          stroke: '#5F95FF',
          strokeWidth: 2,
          rx: 8,
          ry: 8,
        },
        label: {
          fontSize: 12,
          fill: '#333',
          textAnchor: 'middle',
          textVerticalAnchor: 'middle',
        },
      },
      // 添加resize功能
      resizing: {
        enabled: true,
        minWidth: 100,
        minHeight: 60,
        maxWidth: 800,
        maxHeight: 600,
        orthogonal: false,
        restrict: false,
        preserveAspectRatio: false,
        allowNegative: false,
      },
      ports: {
        groups: {},
        items: [],
      },
    }
    
    const group = this.graph.addNode(groupConfig)
    
    // 为Group节点添加初始业务数据
    if (this.onNodeCreated) {
      const initialData = {
        label: label || '组节点',
        type: 'group',
        inputVariables: [],
        outputVariables: []
      }
      this.onNodeCreated(group.id, initialData)
    }
    
    return group
  }

  /**
   * 根据类型创建节点
   * @param {string} type 节点类型
   * @param {string} label 节点标签
   * @param {number} x X坐标
   * @param {number} y Y坐标
   */
  createNodeByType(type, label, x, y) {
    // 如果是Group节点，使用自定义的Group类
    if (type === 'group') {
      const groupNode = new Group({
        x: x,
        y: y,
        width: 300,
        height: 200,
        label: label || '组节点',
        zIndex: 1,
        data: {
          type: 'group',
          parent: true // 标记为父节点
        }
      })
      
      const node = this.graph.addNode(groupNode)
      
      // 为Group节点添加初始业务数据
      if (this.onNodeCreated) {
        const initialData = {
          label: label || '组节点',
          type: 'group',
          inputVariables: [],
                  outputVariables: []
        }
        this.onNodeCreated(node.id, initialData)
      }
      
      return node
    }
    
    const color = NodeConfig.getFixedColor(type)
    // 如果没有传入标签，默认使用"普通节点"
    const defaultLabel = label || '普通节点'
    const nodeConfig = NodeConfig.getNodeConfig(type, defaultLabel, color)
    
    // 直接使用传入的坐标，不进行居中偏移
    nodeConfig.x = x
    nodeConfig.y = y
    
    const node = this.graph.addNode(nodeConfig)
    
    // 确保设置label属性，并保持位置配置
    node.attr('label/text', defaultLabel)
    node.attr('label/position', {
      name: 'bottom',
      args: {
        y: 10,
      },
    })
    
    // 为节点添加初始业务数据
    if (this.onNodeCreated) {
      const initialData = {
        label: defaultLabel,
        type: type,
        inputVariables: [],
        outputVariables: []
      }
      
      // 如果是HTTP节点，添加固定的输出变量
      if (type === 'HttpV1') {
        initialData.outputVariables = [
          { name: 'response', type: 'object', value: '' },
          { name: 'connectionTime', type: 'number', value: '' },
          { name: 'readTime', type: 'number', value: '' }
        ]
      }
      
      // 如果是判断节点，添加初始判断设置
      if (type === 'judge') {
        initialData.judgeConditions = [
          {
            script: '',
            targetNodeId: ''
          }
        ]
        initialData.defaultNodeId = ''
      }
      
      this.onNodeCreated(node.id, initialData)
    }
    
    return node
  }

  /**
   * 添加连线
   * @param {Object} config 连线配置
   */
  addEdge(config) {
    return this.graph.addEdge(config)
  }

  /**
   * 添加随机连线
   */
  addRandomEdge() {
    const nodes = this.graph.getNodes()
    if (nodes.length < 2) {
      throw new Error('至少需要两个节点才能添加连线')
    }
    
    const source = nodes[Math.floor(Math.random() * nodes.length)]
    const target = nodes[Math.floor(Math.random() * nodes.length)]
    
    if (source === target) {
      throw new Error('不能连接同一个节点')
    }

    const edgeConfig = EdgeConfig.getEdgeConfig(source, target, this.currentEdgeType)
    return this.graph.addEdge(edgeConfig)
  }

  /**
   * 全选
   */
  selectAll() {
    this.graph.select(this.graph.getNodes())
    this.updateSelectedCount()
  }

  /**
   * 取消选择
   */
  clearSelection() {
    this.graph.unselect()
    this.updateSelectedCount()
  }

  /**
   * 删除选中元素
   */
  deleteSelected() {
    const selectedCells = this.graph.getSelectedCells()
    if (selectedCells.length > 0) {
      // 过滤掉开始和结束节点，防止被删除
      const cellsToRemove = selectedCells.filter(cell => {
        if (cell.isNode()) {
          const label = cell.attr('label/text')
          return label !== '开始' && label !== '结束'
        }
        return true // 连线可以删除
      })
      
      if (cellsToRemove.length > 0) {
        this.graph.removeCells(cellsToRemove)
        this.updateSelectedCount()
        
        // 检查是否需要自动连接开始和结束节点
        this.checkAndConnectStartEnd()
        
        return cellsToRemove.length
      }
    }
    return 0
  }

  /**
   * 清空画布
   */
  clearGraph() {
    this.graph.clearCells()
    
    // 清空后重新创建开始和结束节点
    setTimeout(() => {
      this.createStartEndNodes()
    }, 100)
  }

  /**
   * 居中显示
   */
  centerContent() {
    this.graph.centerContent()
  }

  /**
   * 放大
   */
  zoomIn() {
    this.graph.zoom(0.2)
    this.currentZoom = this.graph.zoom()
  }

  /**
   * 缩小
   */
  zoomOut() {
    this.graph.zoom(-0.2)
    this.currentZoom = this.graph.zoom()
  }

  /**
   * 重置缩放
   */
  resetZoom() {
    this.graph.zoom(0)
    this.graph.centerContent()
    this.currentZoom = this.graph.zoom()
  }

  /**
   * 导出SVG
   */
  exportSVG() {
    return new Promise((resolve) => {
      this.graph.toSVG((dataUri) => {
        DataUri.downloadDataUri(DataUri.svgToDataUrl(dataUri), 'graph.svg')
        resolve(dataUri)
      }, {
        preserveDimensions: true,
        copyStyles: true,
        stylesheet: `
          .x6-node {
            fill: #fff;
          }
          .x6-edge {
            stroke: #5F95FF;
          }
        `
      })
    })
  }

  /**
   * 导出PNG
   */
  exportPNG() {
    return new Promise((resolve) => {
      this.graph.toPNG((dataUri) => {
        DataUri.downloadDataUri(dataUri, 'graph.png')
        resolve(dataUri)
      }, {
        width: 1200,
        height: 800,
        backgroundColor: '#ffffff',
        padding: {
          top: 20,
          right: 20,
          bottom: 20,
          left: 20,
        },
        quality: 0.92
      })
    })
  }

  /**
   * 导出JPEG
   */
  exportJPEG() {
    return new Promise((resolve) => {
      this.graph.toJPEG((dataUri) => {
        DataUri.downloadDataUri(dataUri, 'graph.jpg')
        resolve(dataUri)
      }, {
        width: 1200,
        height: 800,
        backgroundColor: '#ffffff',
        padding: {
          top: 20,
          right: 20,
          bottom: 20,
          left: 20,
        },
        quality: 0.9
      })
    })
  }

  /**
   * 设置连线类型
   * @param {string} type 连线类型
   */
  setEdgeType(type) {
    this.currentEdgeType = type
  }

  /**
   * 设置拖拽状态
   * @param {boolean} isDragging 是否拖拽中
   * @param {string} dragType 拖拽类型
   */
  setDragState(isDragging, dragType = '') {
    this.isDragging = isDragging
    this.dragType = dragType
  }

  /**
   * 撤销
   */
  undo() {
    if (this.canUndo()) {
      this.graph.undo()
    }
  }

  /**
   * 重做
   */
  redo() {
    if (this.canRedo()) {
      this.graph.redo()
    }
  }

  /**
   * 是否可以撤销
   */
  canUndo() {
    return this.graph.canUndo()
  }

  /**
   * 是否可以重做
   */
  canRedo() {
    return this.graph.canRedo()
  }

  /**
   * 清空历史
   */
  clearHistory() {
    this.graph.cleanHistory()
  }

  /**
   * 是否启用历史
   */
  isHistoryEnabled() {
    return this.graph.isHistoryEnabled()
  }

  /**
   * 启用历史
   */
  enableHistory() {
    this.graph.enableHistory()
  }

  /**
   * 禁用历史
   */
  disableHistory() {
    this.graph.disableHistory()
  }

  /**
   * 切换历史状态
   */
  toggleHistory() {
    this.graph.toggleHistory()
  }

  /**
   * 创建开始和结束节点
   */
  createStartEndNodes() {
    // 开始节点
    const startNode = this.createNodeByType('start', '开始', 100, 200)
    
    // 结束节点
    const endNode = this.createNodeByType('end', '结束', 400, 200)
    
    // 为开始节点添加初始业务数据
    if (startNode) {
      // 通知父组件更新业务数据
      if (this.onNodeCreated) {
        this.onNodeCreated(startNode.id, {
          label: '开始',
          type: 'start',
          inputVariables: [],
          outputVariables: []
        })
      }
    }
    
    // 为结束节点添加初始业务数据
    if (endNode) {
      // 通知父组件更新业务数据
      if (this.onNodeCreated) {
        this.onNodeCreated(endNode.id, {
          label: '结束',
          type: 'end',
          inputVariables: [],
          outputVariables: []
        })
      }
    }
    
    // 连接开始和结束节点
    try {
      const edge = this.addEdge({
        source: startNode.id,
        target: endNode.id,
        attrs: {
          line: {
            stroke: '#5F95FF',
            strokeWidth: 2,
            targetMarker: {
              name: 'block',
              width: 12,
              height: 8,
            },
          },
        },
      })
      
      // 为创建的边添加+号图标
      if (edge) {
        this.addPlusIconToEdge(edge)
      }
    } catch (error) {
      console.warn('连接开始和结束节点失败:', error)
    }
  }

  /**
   * 重新连接节点到组内的新节点
   * @param {Node} groupNode 组内的新节点
   * @param {Node} sourceNode 源节点（可选，默认查找开始节点）
   * @param {Node} targetNode 目标节点（可选，默认查找结束节点）
   */
  reconnectStartEndToGroupNode(groupNode, sourceNode = null, targetNode = null) {
    const nodes = this.graph.getNodes()
    
    // 如果没有指定源节点和目标节点，则查找开始和结束节点
    if (!sourceNode) {
      sourceNode = nodes.find(node => node.attr('label/text') === '开始')
    }
    if (!targetNode) {
      targetNode = nodes.find(node => node.attr('label/text') === '结束')
    }
    
    if (!sourceNode || !targetNode) {
      return
    }
    
    // 获取所有边
    const edges = this.graph.getEdges()
    
    // 删除源节点到目标节点的直接连接
    const directEdge = edges.find(edge => 
      edge.getSourceCellId() === sourceNode.id && 
      edge.getTargetCellId() === targetNode.id
    )
    
    if (directEdge) {
      this.graph.removeEdge(directEdge)
    }
    
    // 获取组内节点的端口
    const groupNodePorts = groupNode.getPorts()
    let inPortId = null
    let outPortId = null
    
    // 查找输入和输出端口
    if (groupNodePorts && groupNodePorts.length > 0) {
      const inPort = groupNodePorts.find(port => port.group === 'in' || port.id === 'in')
      const outPort = groupNodePorts.find(port => port.group === 'out' || port.id === 'out')
      
      if (inPort) {
        inPortId = inPort.id
      }
      if (outPort) {
        outPortId = outPort.id
      }
    }
    
    // 获取源节点的输出端口
    const sourceNodePorts = sourceNode.getPorts()
    let sourceOutPortId = null
    
    // 查找源节点的输出端口
    if (sourceNodePorts && sourceNodePorts.length > 0) {
      const sourceOutPort = sourceNodePorts.find(port => port.group === 'out' || port.id === 'out')
      if (sourceOutPort) {
        sourceOutPortId = sourceOutPort.id
      }
    }
    
    // 获取目标节点的输入端口
    const targetNodePorts = targetNode.getPorts()
    let targetInPortId = null
    
    // 查找目标节点的输入端口
    if (targetNodePorts && targetNodePorts.length > 0) {
      const targetInPort = targetNodePorts.find(port => port.group === 'in' || port.id === 'in')
      if (targetInPort) {
        targetInPortId = targetInPort.id
      }
    }
    
    // 创建新的连接：源节点 -> 组内节点 -> 目标节点
    try {
      // 连接源节点的输出端口到组内节点的输入端口
      const sourceToGroupEdge = this.addEdge({
        source: sourceOutPortId ? { cell: sourceNode.id, port: sourceOutPortId } : sourceNode.id,
        target: inPortId ? { cell: groupNode.id, port: inPortId } : groupNode.id,
        attrs: {
          line: {
            stroke: '#5F95FF',
            strokeWidth: 2,
            targetMarker: {
              name: 'block',
              width: 12,
              height: 8,
            },
          },
        },
      })
      
      // 连接组内节点的输出端口到目标节点的输入端口
      const groupToTargetEdge = this.addEdge({
        source: outPortId ? { cell: groupNode.id, port: outPortId } : groupNode.id,
        target: targetInPortId ? { cell: targetNode.id, port: targetInPortId } : targetNode.id,
        attrs: {
          line: {
            stroke: '#5F95FF',
            strokeWidth: 2,
            targetMarker: {
              name: 'block',
              width: 12,
              height: 8,
            },
          },
        },
      })
      
      // 为新的边添加+号图标，延迟添加确保连线路径已经计算完成
      setTimeout(() => {
        if (sourceToGroupEdge) {
          this.addPlusIconToEdge(sourceToGroupEdge)
        }
        if (groupToTargetEdge) {
          this.addPlusIconToEdge(groupToTargetEdge)
        }
      }, 200)
      
  
      
      return { sourceToGroupEdge, groupToTargetEdge }
    } catch (error) {
      console.warn('重新连接节点失败:', error)
      return null
    }
  }

  /**
   * 检查并连接开始和结束节点
   */
  checkAndConnectStartEnd() {
    const nodes = this.graph.getNodes()
    
    // 如果节点数量不等于2，不需要检查
    if (nodes.length !== 2) {
      return
    }
    
    // 检查是否只有开始和结束节点
    const startNode = nodes.find(node => node.attr('label/text') === '开始')
    const endNode = nodes.find(node => node.attr('label/text') === '结束')
    
    if (!startNode || !endNode) {
      return
    }
    
    // 检查是否已经连接
    const edges = this.graph.getEdges()
    const isConnected = edges.some(edge => 
      edge.getSourceCellId() === startNode.id && 
      edge.getTargetCellId() === endNode.id
    )
    
    // 如果没有连接，则自动连接
    if (!isConnected) {
      try {
        const edge = this.addEdge({
          source: startNode.id,
          target: endNode.id,
          attrs: {
            line: {
              stroke: '#5F95FF',
              strokeWidth: 2,
              targetMarker: {
                name: 'block',
                width: 12,
                height: 8,
              },
            },
          },
        })
        
        // 为自动连接的边添加+号图标
        if (edge) {
          this.addPlusIconToEdge(edge)
        }
        
    
      } catch (error) {
        console.warn('自动连接开始和结束节点失败:', error)
      }
    }
  }

  /**
   * 销毁图形
   */
  dispose() {
    if (this.graph) {
      this.graph.dispose()
    }
  }
} 